<?php

namespace app\common\model;

use think\Db;

/**
 * 账单数据模型
 */
class Receipt extends BaseModel
{
    protected function base($query)
    {
        $query->order('receipt_id', 'desc');
    }

    /**
     * 获取指定用户的账单信息
     * @param int $user_id      用户id
     * @return \think\model\Collection
     */
    public static function detail($user_id){
        return self::get(['user_id'=>$user_id]);
    }

    /**
     * 记录一条账单
     * @param int $user_id   用户id
     * @param array $bill   金额变更信息：{price,reason}
     * @param bool $operation     操作方式：false充值/true提现
     */
    public static function writeBill($user_id, $bill, $operation = false){
        $receipt = self::getNewBill($user_id);
        $data = [
            'user_id'   => $user_id,
            'change_price'  => $bill['price'],
            'change_reason' => $bill['reason'],
            'balance'   => $receipt['balance'], // 余额
            'wxapp_id'      => self::$wxapp_id,
        ];
        if($operation){
            $data['balance'] -= $bill['price'];
            $data['operation']  = 2;
        }else{
            $data['balance'] += $bill['price'];
        }
        $new_receipt = new self;
        Db::startTrans();
        try {
            isset($receipt['symbol']) && $receipt->save(['symbol' => 2]);
            $new_receipt->save($data);
            Db::commit();
            return true;
        } catch (\Exception $th) {
            Db::rollback();
            throw $th;
        }
    }

    /**
     * 获取余额
     * @param int $user_id   用户id
     * @return Receipt|array
     */
    public static function getNewBill($user_id){
        $bill = self::where('user_id', $user_id)
        ->where('symbol', 1)
        ->value('balance');
        if(empty($bill)){// 初始化账单数据
            $bill = ['balance' => 0];
        }
        return $bill;
    }

    /**
     * 提现中的金额
     */
    public static function getWithdrawBill($user_id){
        return self::where('user_id', $user_id)
        ->where('operation', 2)
        ->where('receipt_status', 10)
        ->sum('change_price');
    }
}